package com.atguigu.Mytest;


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class MyCache{
    volatile Map<String,String> map = new HashMap<>();
    ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock();

    public void read(String key){
        rwlock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"正在读");
            map.get(key);
            System.out.println(Thread.currentThread().getName()+"结束读");
        } finally {
            rwlock.readLock().unlock();
        }

    }

    public void write(String key,String value){
        rwlock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"正在写");
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"结束写");
        } finally {
            rwlock.writeLock().unlock();
        }
    }

}

public class ReentrantReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        for (int i = 0; i <10 ; i++) {
            int number = i;
            new Thread(()->{
                myCache.write(number+"",number+"");
            },String.valueOf(i)).start();
        }

        for (int i = 0; i <10 ; i++) {
            int number = i;
            new Thread(()->{
                myCache.read(number+"");
            },String.valueOf(i)).start();
        }

    }
}
